﻿using System;
using System.Data;
using System.Runtime.Serialization;
using Titan.Data;


namespace Titan.Serialization
{
    internal class DataSetSurrogateSelector : ISurrogateSelector
    {
        public DataSetSurrogateSelector()
            : base()
        { }

        public void ChainSelector(ISurrogateSelector selector)
        {
            _next = selector;
        }

        public ISurrogateSelector GetNextSelector()
        {
            return _next;
        }

        public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
        {
            if (type == typeof(DataSet) || type.IsSubclassOf(typeof(DataSet)))
            {
                if (type != typeof(SurrogatedDataSet))
                {
                    selector = this;
                    return DataSetSerializationSurrogate.Default;
                }
            }

            if (null != _next)
                return _next.GetSurrogate(type, context, out selector);

            selector = null;
            return null;
        }

        private ISurrogateSelector _next;

        private class DataSetSerializationSurrogate : ISerializationSurrogate
        {
            public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
            {
                DataSet dataSet = (DataSet)obj;
                DataSerializer.Serialize(dataSet, info, context);
            }

            public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
            {
                DataSet dataSet = (DataSet)obj;
                DataSerializer.Deserialize(dataSet, info, context);
                return dataSet;
            }

            public static readonly DataSetSerializationSurrogate Default = new DataSetSerializationSurrogate();
        }
    }
}
